package com.sgb.kjwl.view.ui.fragment.transport;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentGoodsBinding;
import com.sgb.kjwl.di.transport.DaggerTransportFragComponent;
import com.sgb.kjwl.di.transport.TransportFragModule;
import com.sgb.kjwl.model.entity.CarInfo;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.activity.self.carMaster.BusinessOpportunitySubscriptionActivity;
import com.sgb.kjwl.view.ui.activity.self.logistics.AddCarActivity;
import com.sgb.kjwl.view.ui.activity.transport.driver.trans.TransPushActivity;
import com.sgb.kjwl.view.ui.activity.vehicleManagement.AddDriverInfoActivity;
import com.sgb.kjwl.view.widget.GoodsTypePopWindow3;
import com.sgb.kjwl.viewmodel.transport.GoodsModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import javax.inject.Inject;

import static com.sgb.kjwl.view.widget.GoodsMoreFilterPopWindow.DEFAULT_GOODS_TYPE;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link GoodsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class GoodsFragment extends AppFragment {
    @Inject
    GoodsModel goodsInfoModel;
    //Fragment的View加载完毕的标记
    private boolean isViewCreated;
    //Fragment对用户可见的标记
    private boolean isUIVisible;
    FragmentGoodsBinding binding;

    private GoodsListFragment contentFragment;
    private int tabSelectPosition = 0;
    private String tabGoodsType = DEFAULT_GOODS_TYPE;
    private String driver = "";
    private GoodsTypePopWindow3 goodsTypePopWindow;
    List<GoodsInfoTypeEntity3> goodsInfoTypeEntity3List;
    int pattern;//0-普通，1-竞价，3-自营
    private List<CarInfo> carInfo;
    private boolean isShowFilterData = true;
    private String websiteNo;
    private String websiteType;
    boolean isShowMoreFilter = true;
    boolean canRefresh = true;

    public GoodsFragment() {
    }


    public static GoodsFragment newInstance(String pattern) {
        GoodsFragment fragment = new GoodsFragment();
        Bundle args = new Bundle();
        args.putString("pattern", pattern);
        fragment.setArguments(args);
        return fragment;
    }

    public static GoodsFragment newInstance(String pattern, boolean isShowFilterData, boolean isShowMoreFilter, boolean canRefresh) {
        GoodsFragment fragment = new GoodsFragment();
        Bundle args = new Bundle();
        args.putString("pattern", pattern);
        args.putBoolean("isShowFilterData", isShowFilterData);
        args.putBoolean("isShowMoreFilter", isShowMoreFilter);
        args.putBoolean("canRefresh", canRefresh);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 用户前台主页--物流需求列表（自营）
     *
     * @param websiteType 主页身份（个人、企业、团队）
     * @param websiteNo   身份no
     * @return
     */
    public static GoodsFragment newInstance(String websiteType, String websiteNo) {
        GoodsFragment fragment = new GoodsFragment();
        Bundle args = new Bundle();
        args.putString("websiteType", websiteType);
        args.putString("websiteNo", websiteNo);
        args.putString("pattern", "3");
        args.putBoolean("isShowFilterData", true);
        args.putBoolean("isShowMoreFilter", false);
        args.putBoolean("canRefresh", true);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            isShowFilterData = getArguments().getBoolean("isShowFilterData", true);
            isShowMoreFilter = getArguments().getBoolean("isShowMoreFilter", true);
            canRefresh = getArguments().getBoolean("canRefresh", true);
            String param1 = getArguments().getString("pattern");
            websiteNo = getArguments().getString("websiteNo");
            websiteType = getArguments().getString("websiteType");
            if (param1.equals("2")) {
                pattern = 1;
            } else if (param1.equals("1")) {
                pattern = 0;
            } else {
                pattern = 3;
            }
        }
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerTransportFragComponent.builder()
                .appComponent(appComponent)
                .transportFragModule(new TransportFragModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_goods, container, false);
        binding.line2.setVisibility(pattern==3?View.GONE:View.VISIBLE);
        return binding.getRoot();
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        FragmentManager manager = getChildFragmentManager();
        if (contentFragment == null) {
            if (pattern == 3) {//前台主页--自营列表
                contentFragment = GoodsListFragment.newInstance(websiteType, websiteNo);
            } else {//物流首页--列表
                contentFragment = GoodsListFragment.newInstance(DEFAULT_GOODS_TYPE, pattern, isShowFilterData, isShowMoreFilter, canRefresh);
            }
            manager.beginTransaction().add(R.id.fragment_content_layout, contentFragment).commit();
        }
        isViewCreated = true;
        lazyLoad();
    }

//    public SetUpLayout1 setUpLayout1;
//    public interface SetUpLayout1 {
//        void upLayput1();
//    }
//
//    public void onUpLayout(SetUpLayout1 setUpLayout) {
//        this.setUpLayout1 = setUpLayout;
//    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        //isVisibleToUser这个boolean值表示:该Fragment的UI 用户是否可见
        if (isVisibleToUser) {
            isUIVisible = true;
            lazyLoad();
        } else {
            isUIVisible = false;
        }
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        binding.editView.setOnClickListener(this);
        binding.tvTransPush.setOnClickListener(this);
        binding.tvChance.setOnClickListener(this);
        initTypePopWindow();
        initTabLayout();

        driver = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.DRIVER_AUTH, "");
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
     /*   //当用户未登录时，不允许访问此接口
        if (!"".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            goodsInfoModel.getCarInfo();
        }*/
    }


    private void initTypePopWindow() {
        //货物类型
        goodsTypePopWindow = new GoodsTypePopWindow3(getActivity());
        goodsTypePopWindow.setBgView(binding.grayLayout);
        goodsTypePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
                GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) type;
                binding.tablayout.selectTab(binding.tablayout.getTabAt((int) key2));
            }
        });
        goodsTypePopWindow.setOnDismissListener(() ->
                binding.editView.setImageResource(R.mipmap.icon_tab_unfold));
    }

    private void initTabLayout() {
        //货物类型
        binding.tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                if (null == goodsInfoTypeEntity3List && goodsInfoTypeEntity3List.size() == 0) {
                    return;
                }
                tabSelectPosition = tab.getPosition();
                goodsTypePopWindow.setDefItem(tabSelectPosition);

                String currentGoodsType = goodsInfoTypeEntity3List.get(tab.getPosition()).getNo();
                boolean goodsTypeIsChanged = !tabGoodsType.equals(currentGoodsType);
                tabGoodsType = TextUtils.isEmpty(currentGoodsType) ? DEFAULT_GOODS_TYPE : currentGoodsType;

                if (goodsTypeIsChanged) {
                    contentFragment.refreshContentData(tabGoodsType, pattern);
                }
            }


            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.edit_view:
                binding.editView.setImageResource(R.mipmap.icon_tab_pack_up);
                if (null == goodsInfoTypeEntity3List || goodsInfoTypeEntity3List.size() == 0)
                    return;
                EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_LOGISTICS_WINDOW_TOP));
                goodsTypePopWindow.setData(goodsInfoTypeEntity3List, binding.tablayout.getSelectedTabPosition());
                new Handler().postDelayed(() -> goodsTypePopWindow.showPopwindow(binding.editView, 0, 0), 400);
                break;
            case R.id.tv_trans_push://推送承运
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    EventBus.getDefault().postSticky("transport_to_login");
                } else {
                    if (driver.equals("SUCCESS")) {
                        if (carInfo != null && carInfo.size() > 0) {
                            TransPushActivity.start(getActivity());
                        } else {
                            showDialog("nocar");
                        }
                    } else {
                        switch (driver) {
                            case "FAIL":
                                showDialog("driverFail");
                                break;
                            case "STANDBY":
                                showDialog("driverStandby");
                                break;
                            default:
                                showDialog("driver");
                                break;
                        }
                    }
                }
                break;
            case R.id.tv_chance://货源商机
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    EventBus.getDefault().postSticky("transport_to_login");
                } else {
                    if (driver.equals("SUCCESS")) {
                        BusinessOpportunitySubscriptionActivity.start(getActivity());
                    } else {
                        switch (driver) {
                            case "FAIL":
                                showDialog("driverFail");
                                break;
                            case "STANDBY":
                                showDialog("driverStandby");
                                break;
                            default:
                                showDialog("driver");
                                break;
                        }
                    }
                }
                break;

        }
    }

    private void lazyLoad() {
        //这里进行双重标记判断,是因为setUserVisibleHint会多次回调,并且会在onCreateView执行前回调,必须确保onCreateView加载完毕且页面可见,才加载数据
        if (isViewCreated && isUIVisible) {
            loadData();
            //数据加载完毕,恢复标记,防止重复加载
            isViewCreated = false;
            isUIVisible = false;
        }
    }


    private void loadData() {
        goodsInfoModel.getGoodsType3();
    }


    //获取货物类型后更新数据
    public void getGoodsTypeData(List<GoodsInfoTypeEntity3> list) {
        if (null != list && list.size() > 0) {
            refreshFragmentContent(list);
        } else {
            MToast.showToast(getActivity(), "数据未加载");
        }
    }

    private void refreshFragmentContent(List<GoodsInfoTypeEntity3> list) {
        goodsInfoTypeEntity3List = list;

        binding.tablayout.removeAllTabs();
        for (int i = 0; i < list.size(); i++) {
            binding.tablayout.addTab(binding.tablayout.newTab().setText(list.get(i).getName()));
        }
        binding.tablayout.selectTab(binding.tablayout.getTabAt(0));
        binding.tablayout.scrollTo(0, 0);
    }

    public void showDialog(String type) {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失

        TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_logout_confirm = (TextView) view.findViewById(R.id.tv_logout_confirm);
        tv_title.setVisibility(View.VISIBLE);
        TextView tv_logout_cancel = (TextView) view.findViewById(R.id.tv_logout_cancel);
        if (type.equals("driver")) {
            tv_title.setText("认证");
            tv_message.setText("请先进行司机认证再操作");
        } else if (type.equals("nocar")) {
            tv_title.setText("无可用车辆");
            tv_message.setText("请先添加车辆");
            tv_logout_confirm.setText("去添加");
        } else if (type.equals("driverFail")) {
            tv_title.setText("司机认证不通过");
            tv_message.setText("请重新提交认证信息");
        } else if (type.equals("driverStandby")) {
            tv_title.setText("司机认证审核中");
            tv_message.setText("认证通过后才能操作");
        }
        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type.equals("driver")) {

                    Intent intent = new Intent(getActivity(), AddDriverInfoActivity.class);
                    startActivity(intent);
                } else if (type.equals("nocar")) {
                    AddCarActivity.start(getActivity());
                }

                roundCornerDialog.dismiss();
            }
        });

        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    public void showCarInfo(List<CarInfo> carInfo) {
        this.carInfo = carInfo;

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LogisticsEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_LOGISTICS_REFRESH) {
            loadData();
        }
    }

}